<?php

class DefaultController extends Controller
{
	public function actionIndex()
	{
		$model=new Events('search');
		$model->unsetAttributes();
		if(isset($_GET['Events']))
			$model->attributes=$_GET['Events'];

		$this->render('index', array(
			'model'=>$model
		));
	}
	
	public function actionEventMembers($id)
	{
		if(isset($_GET['id'])){
			$member = Members::model()->findByPk($id);
			$criteria = new CDbCriteria;
			$criteria->condition = 'status="A" AND member_id = "'.$_GET['id'].'"';
			$dataProvider=new CActiveDataProvider('Events',
				array(
					'criteria'=>$criteria,
					'sort'=>array(
						'defaultOrder'=>'startdate ASC, enddate DESC',
					),
					'pagination'=>array(
						'pageSize'=>10,
						'pageVar'=>'page',
					),
				)
			);
			$this->render('eventMembers',array('dataProvider'=>$dataProvider,'member'=>$member));
		}
	}
    
	public function actionView($id){
		$model = Events::model()->findByPk($id);
        $seo = SeoTools::model()->findByAttributes(array('table_id'=>$id,'tables'=>'events'));
        $location = EventLocations::model()->findByAttributes(array('event_id'=>$id));
        $ticket = EventTickets::model()->findAllByAttributes(array('event_id'=>$id));
        $content = EventContent::model()->findByAttributes(array('event_id'=>$id));
        $category = EventCategories::model()->findByAttributes(array('event_id'=>$id));
        $nameCategory = Categories::model()->findByPk($category->category_id);
        $this->render('view',array('model'=>$model,
            'seo'=>$seo,'location'=>$location,'ticket'=>$ticket,
            'content'=>$content,'nameCategory'=>$nameCategory->title
            ));
	}

	public function actionAjaxupdate()
	{
	    $act = $_GET['act'];
	    $autoIdAll = $_POST['autoId'];
	        if(count($autoIdAll)>0)
	        {
	            foreach($autoIdAll as $autoId)
	            {
	                $model=Events::model()->findByPk($autoId);
	                if($act=='doPendding')
	                    $model->status = 'I';
	                if($act=='doActive')
	                    $model->status = 'A';
	                if($act=='doInactive')
	                    $model->status = 'P';                     
	                if($model->save(false))
	                    echo 'ok';
	                else
	                    throw new Exception("Sorry",500);
	 
	            }
	        }
	}

	public function actionUpdateValue($id)
	{
		if(isset($_GET['id'])){
		    $act = $_GET['act'];
		    $id = $_GET['id'];
	        $model=Events::model()->findByPk($id);
	        if($act=='doPendding')
	            $model->status = 'I';
	        if($act=='doActive')
	            $model->status = 'A';
	        if($act=='doInactive')
	            $model->status = 'P';  
	        if($act== 'doSlide')
	        	$model->featured = 'Y';    
	        if($act== 'doTopEvent')
	        	$model->hot = 'Y'; 
	        if($act== 'doHomePage')
	        	$model->homepage = 'Y';                
	        if($model->save(false)){
	        	$index =new Events('search');
				$index->unsetAttributes();
				if(isset($_GET['Events']))
					$index->attributes=$_GET['Events'];
	            $this->render('index',array('model'=>$index));
	        }
	        else
	            throw new Exception("Sorry",500);
	    }
	}

    public function actionCreate()
	{
		$model = new Events('create');
		$category = new EventCategories;
		$chart = new EventCharts;
		$contact = new EventContact;
		$content = new EventContent;
        $label = new Labels;
		$location = new EventLocations;
		$ticket = new EventTickets;
        $seotool = new SeoTools;
        
        $model->startdate = date('Y-m-d H:i:s', round(time() / (15 * 60)) * (15 * 60));
        $model->enddate = date('Y-m-d H:i:s', round((time() + 4 * 3600) / (15 * 60)) * (15 * 60));
        
		if (isset($_POST['Events'])) {
			$model->attributes = $_POST['Events'];
            $model->title = trim($model->title, ' ,.');
			$model->code = '';
			$model->othertitle = $model->title;
			$model->discount = 'N';
			$model->type = 'P';
			$model->numlike = 0;
			$model->numdislike = 0;
			$model->numviews = 0;
			$model->numcomments = 0;
			$model->hot = 'N';
			$model->featured = 'N';
			$model->homepage = 'N';
			$model->status = 'D';
			$model->url = $this->createSlug($model->title);
			$model->posteddate = date('Y-m-d H:i:s');
            $model->updatedate = date('Y-m-d H:i:s');
			$model->member_id = Yii::app()->user->id;
			// Save image here
			$imagePath = IMAGES_DIR . 'events/original/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile = CUploadedFile::getInstance($model, 'image');
            if ($model->title !== '') {
                if ($imageUploadFile !== null) {
                    $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                    if (!file_exists($imagePath)) {
                        mkdir($imagePath, 0777, true);
                    }
                    $imageUploadFile->saveAs($imagePath . $model->image);
                    // Resize images
                    //$this->resizeImage($imagePath, $model->image, date('Y-m-d H:i:s'));
                }
                else {
                    if (isset($_POST['Events']['currentImage'])) {
                        $image = $_POST['Events']['currentImage'];
                        $model->image = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                        copy($imagePath . $image, $imagePath . $model->image);
                        // Resize images
                        $this->resizeImage($imagePath, $model->image, date('Y-m-d H:i:s'));
                    }
                }
            }
			// Save time here
			$startdate = explode('-', $_POST['startdate']);
			$model->startdate = $startdate['2'] . '-' . $startdate['1'] . '-' . $startdate['0'] . ' ' . $_POST['starttime'];
			$enddate = explode('-', $_POST['enddate']);
			$model->enddate = $enddate['2'] . '-' . $enddate['1'] . '-' . $enddate['0'] . ' ' . $_POST['endtime'];
			
			// Save the content
			$content->attributes = $_POST['EventContent'];
			/*
			$imagePath = IMAGES_DIR . 'contents/' . date('Ymd', strtotime($model->posteddate)) . '/';
			if (!file_exists($imagePath)) {
				mkdir($imagePath, 0777, true);
			}
			preg_match_all('/\<img(.*)src\=\"([^\"]+)\"(.*)\>/', $content->description, $matches, PREG_SET_ORDER);

			foreach ($matches as $key => $images) {
				// Save images
				$filePath = pathinfo($images[2]);
				$imageName = $model->url . '_' . ($key + 1) . '.' . $filePath['extension'];
				$fp = fopen($imagePath . $imageName, 'wb');
				fclose($fp);
				copy($images[2], $imagePath . $imageName);
				// Replace in content
				$content->description = str_replace($images[0], '<img src="/images/news/' . date('Ymd', strtotime($model->posteddate)) . '/' . $imageName . '" alt="' . $model->title . '" /><br />', $content->description);
			}
			*/
			$location->attributes = $_POST['EventLocations'];
            $location->event_id = 0;
            $location->place_id = 0;
            $location->location = 'N/A';
            $location->district_id = 0;
            $location->city_id = 0;
            $location->country_id = 0;
            $location->map = 'N/A';
            $location->phone = '';
            $location->altphone = '';
            $location->fax = '';
            $location->direction = '';
            // Get tags
            $tags = $_POST['Labels']['title'];
            $tags = explode(',', $tags);
            $labels = '';
            foreach ($tags as $data) {
                $temp = Labels::model()->findByPk($data);
                if (!empty($temp)) {
                    $labels .= $temp->id . ':' . $temp->title . ',';
                }
                else {
                    $labels .= $data . ':' . $data . ',';
                }
            }
            $labels = substr($labels, 0, -1);
            Yii::app()->session['tags'] = $labels;
            $seotool->attributes = $_POST['SeoTools'];
			// Save event
			if ($model->validate() && $content->validate()) {
                $model->save();
				// Save category
				$category->event_id = $model->id;
				$category->category_id = $_POST['EventCategories']['category_id'];
				$category->isprimary = 'Y';
				$category->save();
				//Save chart
				$imageUploadFile = CUploadedFile::getInstance($chart, 'image');
				if ($imageUploadFile !== null) {
					$imageChartPath = IMAGES_DIR . 'events/charts/' . date('Ymd', strtotime($model->posteddate)) . '/';
					$chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
					if (!file_exists($imageChartPath)) {
						mkdir($imageChartPath, 0777, true);
					}
					$imageUploadFile->saveAs($imageChartPath . $chart->image);
					// Resize images
					$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
					$chart->event_id = $model->id;
					$chart->title = $model->title;
					if ($chart->validate()) {
						$chart->save();
					}
				}
				// Save contact
				foreach ($_POST['EventContact']['prename'] as $x => $data) {
					$xResult = array(
						'prename'=>$data,
						'company'=>$_POST['EventContact']['company'][$x],
						'fullname'=>$_POST['EventContact']['fullname'][$x],
						'phone'=>$_POST['EventContact']['phone'][$x],
					);
					
					$xData = new EventContact;
					$xData->attributes = $xResult;
					$xData->event_id = $model->id;
					$xData->agent_id = 0;
					$xData->email = 'N/A';
					$xData->altphone = '';
					$xData->address = 'N/A';
					$xData->brief = 'N/A';
					if ($xData->validate()) {
						$xData->save();
					}
					else {
						//break;
					}
				}
				// Save content
				$content->event_id = $model->id;
				$content->save();
				// Save location
				$location->event_id = $model->id;
				
				if ($location->validate()) {
					$location->save();
				}
				// Save ticket
				if ($model->ticket !== 'F') {
					foreach ($_POST['EventTickets']['title'] as $x => $data) {
						$xResult = array(
							'title'=>$data,
							'price'=>$_POST['EventTickets']['price'][$x],
						);
						
						$xData = new EventTickets;
						$xData->attributes = $xResult;
						$xData->event_id = $model->id;
						$xData->brief = '';
						$xData->quantity = 100;
						$xData->minorder = 1;
						$xData->maxorder = 10;
						$xData->priceoff = 0;
						$xData->percentoff = 0;
						$xData->startsale = date('Y-m-d H:i:s');
						$xData->endsale = date('Y-m-d H:i:s');
						$xData->position = 0;
						$xData->outofstock = 'N';
						$xData->status = 'D';
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
				}
				
				// Save SEOTool
				$seotool->description = substr($seotool->description, 0, 255);
				$seotool->metarobot = '';
				$seotool->tables = 'events';
				$seotool->table_id = $model->id;
				$seotool->status = 'A';
				$seotool->posteddate = date('Y-m-d H:i:s');
				if ($seotool->validate()) {
					$seotool->save();
				}
                // Save tags
                foreach ($tags as $data) {
                    $temp1 = Labels::model()->findByPk($data);
                    if (!empty($temp1)) {
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $data;
                        $yData->type = 'E';
                        $yData->save();
                    }
                    else {
                        // Save new label
                        $xData = new Labels;
                        $xData->title = trim($data);
                        $xData->slug = $this->createSlug($data);
                        $xData->posteddate = $xData->updatedate = date('Y-m-d H:i:s');
                        $xData->save();
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $xData->id;
                        $yData->type = 'E';
                        $yData->save();
                    }
                }
                Yii::app()->session['tags'] = null;
				// View Event
				$this->redirect(array('/Events/default/view', 'id'=>$model->id));
			}
		}
		
		$this->render('create', array(
			'model'=>$model,
			'category'=>$category,
			'chart'=>$chart,
			'contact'=>$contact,
			'content'=>$content,
            'label'=>$label,
			'location'=>$location,
			'ticket'=>$ticket,
            'seotool'=>$seotool
		));
	}
    
	public function actionUpdate($id){
		$model = Events::model()->findByPk($id);
		
		if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}
		
		$model->scenario = 'update';
		$chart = new EventCharts;
        $contact = new EventContact;
        $label = new Labels;
		
		if (isset($_POST['Events'])) {
			$model->attributes = $_POST['Events'];
            $model->title = trim($model->title, ' ,.');
			$model->url = $this->createSlug($model->title);
            $model->updatedate = date('Y-m-d H:i:s');
			// Save image here
			$imagePath = IMAGES_DIR . 'events/original/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile = CUploadedFile::getInstance($model, 'image');
			
			$model->image = $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION);
            // Kiểm tra nếu có upload file mới
			if ($model->title !== '') {
                if ($imageUploadFile !== null) {
                    $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                    if (!file_exists($imagePath)) {
                        mkdir($imagePath, 0777, true);
                    }
                    $imageUploadFile->saveAs($imagePath . $model->image);
                    // Resize images
                    $this->resizeImage($imagePath, $model->image, $model->posteddate);
                }
                else {// Change file name nếu không thay đổi
                    if ($model->image !== $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION)) {
                        copy($imagePath . $model->image, $imagePath . $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION));
                        unlink($imagePath . $model->image);
                        $model->image = $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION);
                        // Resize images
                        $this->resizeImage($imagePath, $model->image, $model->posteddate);   
                    }
                }
            }
            
			// Save time here
			$startdate = explode('-', $_POST['startdate']);
			$model->startdate = $startdate['2'] . '-' . $startdate['1'] . '-' . $startdate['0'] . ' ' . $_POST['starttime'];
			$enddate = explode('-', $_POST['enddate']);
			$model->enddate = $enddate['2'] . '-' . $enddate['1'] . '-' . $enddate['0'] . ' ' . $_POST['endtime'];
			
			// Save the content
			$model->content->attributes = $_POST['EventContent'];

			// Save event
			if ($model->validate() && $model->save()) {
				// Save category
				$model->eventCategory->category_id = $_POST['EventCategories']['category_id'];
				$model->eventCategory->save();
				//Save chart
				$imageChartPath = IMAGES_DIR . 'events/charts/' . date('Ymd', strtotime($model->posteddate)) . '/';
				$imageUploadFile = CUploadedFile::getInstance($chart, 'image');
				if ($imageUploadFile !== null) {
					if (isset($model->chart)) {
						$model->chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
						if (!file_exists($imageChartPath)) {
							mkdir($imageChartPath, 0777, true);
						}
						$imageUploadFile->saveAs($imageChartPath . $model->chart->image);
						// Resize images
						$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
						$model->chart->title = $model->title;
						if ($model->chart->validate()) {
							$model->chart->save();
						}
					}
					else {
						$chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
						if (!file_exists($imageChartPath)) {
							mkdir($imageChartPath, 0777, true);
						}
						$imageUploadFile->saveAs($imageChartPath . $chart->image);
						// Resize images
						$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
						$chart->event_id = $model->id;
						$chart->title = $model->title;
						if ($chart->validate()) {
							$chart->save();
						}
					}
				}
				// Save contact
				foreach ($_POST['EventContact']['prename'] as $x => $data) {
					$xResult = array(
						'prename'=>$data,
						'company'=>$_POST['EventContact']['company'][$x],
						'fullname'=>$_POST['EventContact']['fullname'][$x],
						'phone'=>$_POST['EventContact']['phone'][$x],
					);
					
					if (isset($_POST['EventContact']['id'][$x])) {
						$xData = EventContact::model()->findByPk($_POST['EventContact']['id'][$x]);
						$xData->attributes = $xResult;
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
					else {
						$xData = new EventContact;
						$xData->attributes = $xResult;
						$xData->event_id = $model->id;
						$xData->agent_id = 0;
						$xData->email = 'N/A';
						$xData->altphone = '';
						$xData->address = 'N/A';
						$xData->brief = 'N/A';
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
				}
				// Save content
				if ($model->content->validate()) {
					$model->content->save();
				}
				// Save location
				$model->location->attributes = $_POST['EventLocations'];
				
				if ($model->location->validate()) {
					$model->location->save();
				}
				// Save ticket
				if ($model->ticket === 'F') {
					if (!empty($model->tickets)) {
						foreach ($model->tickets as $data) {
							$data->delete();
						}
					}
				}
				else {
					foreach ($_POST['EventTickets']['title'] as $x => $data) {
						$xResult = array(
							'title'=>$data,
							'price'=>$_POST['EventTickets']['price'][$x],
						);
						
						if (isset($_POST['EventTickets']['id'][$x])) {
							$xData = EventTickets::model()->findByPk($_POST['EventTickets']['id'][$x]);
							$xData->attributes = $xResult;
							if ($xData->validate()) {
								$xData->save();
							}
							else {
								//break;
							}
						}
						else {
							$xData = new EventTickets;
							$xData->attributes = $xResult;
							$xData->event_id = $model->id;
							$xData->brief = '';
							$xData->quantity = 100;
							$xData->minorder = 1;
							$xData->maxorder = 10;
							$xData->priceoff = 0;
							$xData->percentoff = 0;
							$xData->startsale = date('Y-m-d H:i:s');
							$xData->endsale = date('Y-m-d H:i:s');
							$xData->position = 0;
							$xData->outofstock = 'N';
							$xData->status = 'A';
							if ($xData->validate()) {
								$xData->save();
							}
							else {
								//break;
							}
						}
					}
				}
				// Save SEOTool
				$model->seotool->title = $model->title;
				$model->seotool->description = $model->brief;
				$model->seotool->keywords = '';
				$model->seotool->metarobot = '';
				if ($model->seotool->validate()) {
					$model->seotool->save();
				}
                // Save tags
                $tags = $_POST['Labels']['title'];
                $tags = explode(',', $tags);
                $tagsList = array();
                foreach ($tags as $data) {
                    $temp1 = Labels::model()->findByPk($data);
                    if (!empty($temp1)) {
                        $tagsList[] = $data;
                        $temp2 = EventLabels::model()->findByAttributes(array('label_id'=>$data, 'event_id'=>$model->id));
                        if (empty($temp2)) {
                            // Save label relation
                            $yData = new EventLabels;
                            $yData->event_id = $model->id;
                            $yData->label_id = $data;
                            $yData->type = 'E';
                            $yData->save();
                        }
                    }
                    else {
                        // Save new label
                        $xData = new Labels;
                        $xData->title = trim($data);
                        $xData->slug = $this->createSlug($data);
                        $xData->posteddate = $xData->updatedate = date('Y-m-d H:i:s');
                        $xData->save();
                        $tagsList[] = $xData->id;
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $xData->id;
                        $yData->type = 'E';
                        $yData->save();
                    }
                }
                foreach ($model->label as $data) {
                    if (!in_array($data->id, $tagsList)) {
                        EventLabels::model()->findByAttributes(array('event_id'=>$model->id, 'label_id'=>$data->id))->delete();
                    }
                }
				// View Event
				$this->redirect(array('/Events/default/view', 'id'=>$model->id));
			}
		}
		
		if (empty($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}
		
		$this->render('update', array(
			'model'=>$model,
			'chart'=>$chart,
            'contact'=>$contact,
            'label'=>$label,
		));
	}
    
    public function actionDelete($id)
    {
        $model = Events::model()->findByPk($id);
        
        $model->delete();
    }
}